package cn.lili.modules.grab.dingdong.facade;

import cn.lili.modules.grab.dingdong.DingdongBase;
import cn.lili.modules.grab.dingdong.DingdongBody;
import cn.lili.modules.grab.dingdong.DingdongContent;
import cn.lili.modules.grab.dingdong.utils.AESUtil;
import cn.lili.modules.grab.dingdong.utils.RSAUtil;
import cn.lili.modules.grab.dingdong.config.DingdongConfig;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Component
@Slf4j
public class DingdongFacade {

    @Resource
    private DingdongConfig dingdongConfig;

    /**
     * 构建DingdongBase对象
     */
    public DingdongBase dingdongBaseBuilder() {
        return DingdongBase.builder()
                .time(String.valueOf(new Date().getTime()))
                .source("99")
                .equipment("产品描述")
                .token(dingdongConfig.getToken())
                .version("v3.2.1")
                .build();
    }

    /**
     * 构建DingdongContent对象
     *
     * @param data 请求内容
     */
    public DingdongContent dingdongContentBuilder(Object data) {
        return DingdongContent.builder()
                .base(dingdongBaseBuilder())
                .data(data)
                .build();
    }

    /**
     * 构建dingdongBody对象
     *
     * @param data 请求对象
     */
    public DingdongBody dingdongBodyBuilder(Object data) {
        try {
            DingdongContent dingdongContent = dingdongContentBuilder(data);
            String requestLock = AESUtil.initkey();
            String requestEncryptedContent = AESUtil.encrypt("\"" + StringEscapeUtils.escapeJava(JSONObject.toJSONString(dingdongContent)) + "\"", requestLock);
            String requestEncryptedLock = RSAUtil.pubEncrypt(requestLock, dingdongConfig.getPublic_key());

            return DingdongBody.builder()
                    .lock(requestEncryptedLock)
                    .content(requestEncryptedContent)
                    .time(String.valueOf(new Date().getTime()))
                    .app_key(dingdongConfig.getApp_key())
                    .build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
